<template>
  <div class="category-manage">
    <!-- 搜索和操作区域 -->
    <div class="operation-bar">
      <div class="search-area">
        <el-input
          v-model="searchModel.keyword"
          placeholder="请输入搜索内容"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="load()">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </div>
      <div class="action-area">
        <el-button type="primary" @click="handleAdd()">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button type="danger" @click="deleteSelected()">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        :data="categoryList"
        stripe
        border
        highlight-current-row
        @selection-change="handleSelectionChangeDepartment"
        class="custom-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        
        <el-table-column
          align="center"
          label="分类ID"
          prop="categoryId"
          width="100"
        />
        
        <el-table-column
          align="center"
          label="分类名"
          prop="categoryName"
          width="200"
        />
        <el-table-column
          align="center"
          label="创建时间"
          prop="createdAt"
          width="300"
          :formatter="formatDate"
        />
        <el-table-column
          align="center"
          label="分类描述"
          prop="description"
          min-width="200"
        />
        
        <el-table-column
          align="center"
          label="操作"
          width="180"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-popconfirm
              title="确定要删除吗?"
              @confirm="handleDelete(scope.row)"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="searchModel.pageNow"
        v-model:page-size="searchModel.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        background
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="30%"
      @close="resetForm"
    >
      <el-form 
        :model="formData" 
        :rules="formRules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input 
            v-model="formData.categoryName" 
            placeholder="请输入分类名称"
          />
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            placeholder="请输入分类描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(this.formData)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import categoryApi from "@/api/category.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus, Delete, Edit } from "@element-plus/icons-vue";

export default {
  components: {
    Plus,
    Delete,
    Edit,
    Search
  },
  data() {
    return {
      categoryList: [],
      totalCount: 0,
      searchModel: {
        pageNow: 1,
        pageSize: 10,
        keyword: "",
      },
      multipleSelectionDepartment: [],
      dialogVisible: false,
      dialogTitle: "新增分类",
      isEditMode: false,
      formData: {
        categoryId: null,
        categoryName: '',
        description: ''
      },
      formRules: {
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      let pageInfo = {
        currentPage: this.searchModel.pageNow,
        pageSize: this.searchModel.pageSize,
        key: this.searchModel.keyword,
      };
      categoryApi.list(pageInfo).then((res) => {
        this.categoryList = res.data.records;
        this.totalCount = res.data.total || 0;
      }).catch(error => {
        console.error('加载分类列表失败:', error);
        ElMessage.error('加载失败，请稍后重试');
      });
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNow = 1;
      this.load();
    },
    handleCurrentChange(pageNow) {
      this.searchModel.pageNow = pageNow;
      this.load();
    },
    handleAdd() {
      this.dialogTitle = "新增分类";
      this.isEditMode = false;
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑分类";
      this.isEditMode = true;
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    submitForm(formData) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;
        
        try {
          const apiMethod = this.isEditMode ? categoryApi.update : categoryApi.add;
          await apiMethod(this.formData);
          
          ElMessage.success(this.isEditMode ? '修改成功' : '新增成功');
          this.dialogVisible = false;
          this.load();
        } catch (error) {
          console.error('操作失败:', error);
          ElMessage.error('操作失败');
        }
      });
    },
    handleDelete(row) {
      ElMessageBox.confirm(
        '确定要删除该分类吗?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        categoryApi.deletePro(row.categoryId).then(() => {
          ElMessage.success('删除成功');
          this.load();
        }).catch(error => {
          console.error('删除失败:', error);
          ElMessage.error('删除失败');
        });
      }).catch(() => {
        // 用户取消操作
      });
    },
    deleteSelected() {
      if (this.multipleSelectionDepartment.length === 0) {
        ElMessage.warning('请至少选择一项');
        return;
      }
      
      ElMessageBox.confirm(
        `确定要删除选中的 ${this.multipleSelectionDepartment.length} 项吗?`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        const ids = this.multipleSelectionDepartment.map(item => item.categoryId);
        categoryApi.deleteBatch(ids).then(() => {
          ElMessage.success('批量删除成功');
          this.load();
          this.multipleSelectionDepartment = [];
        }).catch(error => {
          console.error('批量删除失败:', error);
          ElMessage.error('批量删除失败');
        });
      }).catch(() => {
        // 用户取消操作
      });
    },
    handleSelectionChangeDepartment(val) {
      this.multipleSelectionDepartment = val;
    },
    resetForm() {
      this.$refs.formRef?.resetFields();
      this.formData = {
        categoryId: null,
        categoryName: '',
        description: ''
      };
    },
    formatDate(row, column, cellValue) {
      if (!cellValue) return '-';
      const date = new Date(cellValue);
      return date.toLocaleString();
    }
  }
};
</script>

<style scoped>
.category-manage {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.search-area {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.action-area {
  display: flex;
  gap: 12px;
}

.table-container {
  margin-bottom: 20px;
}

.custom-table {
  width: 100%;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.el-button .el-icon {
  margin-right: 4px;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

:deep(.el-table--striped .el-table__row--striped) {
  background-color: #fafafa;
}

:deep(.el-table--border) {
  border-color: #ebeef5;
}

:deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}
</style>